package com.nf.service;

import com.nf.entity.Course;
import com.nf.dao.CourseDao;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

@Service
public class CourseServiceImpl  implements CourseService{

    //@Autowired
    //private SqlSessionFactory factory;
//@Autowired
    //private CourseDao courseDao;

    private static final int PER_PAGE_SIZE = 10;



    @Autowired
    private CourseDao courseDao;

    @Override
    public List<Course> getAllCourse(int currentPage) {
        RowBounds rowBounds = new RowBounds((currentPage-1)*PER_PAGE_SIZE, PER_PAGE_SIZE);
        List<Course> courseList = courseDao.getAllCourse(rowBounds);
        //session.close();
        return courseList;

    }


    //一共x条记录
    @Override
    public int getRecodeCount() {
        //@Autowried
        //private CourseDao courseDao
        InputStream inputStream = null;
        try {
            inputStream = Resources.getResourceAsStream("config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
        SqlSessionFactory factory = builder.build(inputStream);
        SqlSession session = factory.openSession();
        CourseDao courseDao = session.getMapper(CourseDao.class);
        int recodeCount = courseDao.getRecodeCount();
        session.close();
        return recodeCount;
    }

    //可以分多少页
    @Override
    public int getPageSize() {
        return (getRecodeCount()+PER_PAGE_SIZE-1)/PER_PAGE_SIZE;
    }
}
